<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :xs="15" :sm="18" :md="19" :lg="20" :xl="20">
        <!--工具栏-->
        <div class="head-container">
          <div v-if="crud.props.searchToggle">
            <!-- 搜索 -->
            <el-input
              v-model="query.blurry"
              clearable
              size="small"
              placeholder="输入昵称进行搜索"
              style="width: 200px;"
              class="filter-item"
              @keyup.enter.native="crud.toQuery"
            />
            <rrOperation/>
          </div>
          <crudOperation show="" :permission="permission"/>

  </div>
        <!--表单渲染-->
        <el-dialog append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU"
                   :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="600px">
          <el-form ref="form"  :model="form" :rules="rules"  label-width="80px">
            <el-row>
              <el-col :span="12">
                <div class="grid-content bg-purple">
                  <el-form-item label="年级名称" prop="name">
                    <el-input v-model="form.name" style="width: 370px;" />
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple">

                </div>
              </el-col>
            </el-row>

          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="text" @click="crud.cancelCU">取消</el-button>
            <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
          </div>
        </el-dialog>
        <!--表格渲染-->
        <el-table ref="table" v-loading="crud.loading" :data="crud.data" style="width: 80%;"
                  @selection-change="crud.selectionChangeHandler" >
          <el-table-column :selectable="checkboxT" type="selection" width="55"/>
          <el-table-column :show-overflow-tooltip="true" prop="name" label="年级名称"/>
          <el-table-column :show-overflow-tooltip="true" prop="classNumber" label="班级数量"/>
          <el-table-column
            label="操作"
            width="250"
            align="center"
            fixed="right"
          >
            <template slot-scope="scope">
              <udOperation
                style="display: inline-block"
                :data="scope.row"
                :permission="permission"
              />
              <el-button
                style="display: inline-block;"
                :permission="permission"
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="addClass(scope.row)">
                添加班级
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--分页组件-->
        <pagination/>

        <!--班级列表-->
        <el-dialog  :close-on-click-modal="false" :before-close="clearCache"
                    :visible.sync="showClassList" title="班级列表" width="600px" :destroy-on-close="true">
          <el-button
            v-permission="permission.add"
            class="filter-item"
            size="mini"
            type="primary"
            icon="el-icon-plus"
            @click="showAddDialog"
            style="margin-bottom: 20px"
          >
            新增
          </el-button>
          <el-table :data="classLists" >
            <el-table-column  prop="name" label="班级名称"/>
            <el-table-column v-permission="['admin','dict:edit','dict:del']" label="操作" align="center" fixed="right">
              <template slot-scope="scope">
                <el-button v-permission="permission.edit" size="mini" type="primary" icon="el-icon-edit" @click="editClass(scope.row)" />
                <el-button v-permission="permission.edit" size="mini" type="danger" icon="el-icon-delete" @click="delClass(scope.row)" />
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            layout="prev, pager, next"
            style="float: right"
            :total="classListsTotal">
          </el-pagination>
        </el-dialog>
        <!--编辑班级列表-->
        <el-dialog :append-to-body="true" :close-on-click-modal="false"  :visible.sync="addDialog" title="编辑班级" width="500px" :destroy-on-close="true">
          <el-form ref="classModal" :model="classModal" :rules="rules" size="small" label-width="80px">
            <el-form-item label="班级名称" prop="name">
              <el-input v-model="classModal.name" ></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="text" @click="cancelSave">取消</el-button>
            <el-button type="primary" @click="saveClass">确认</el-button>
          </div>
        </el-dialog>

      </el-col>
    </el-row>
  </div>
</template>

<script>
import crudGrade from '@/api/system/grade'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import DateRangePicker from '@/components/DateRangePicker/index'
import Treeselect from '@riophae/vue-treeselect'
import { mapGetters } from 'vuex'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import appUtils from '@/utils/appUtils'
import { getToken } from '@/utils/auth'
import {add,edit,del} from '@/api/system/class'
import dataUtils from '@/utils/dataUtils'
import {getClassByGradeId} from "@/api/system/grade";

let userRoles = []
const defaultForm = {
  name: null,
  id: null,
}
export default {
  name: 'Grade',
  components: { Treeselect, crudOperation, rrOperation, udOperation, pagination, DateRangePicker },
  cruds() {
    return CRUD({ title: '年级', url: 'admin/SysGrade/page', exportUrl:'admin/sysUser/export-user-list',crudMethod: { ...crudGrade } })
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  // 数据字典
  data() {
    return {
      visible:false,
      /*下载路径*/
      path: process.env.BASE_URL,
      /*上传文件的列表*/
      fileList:[],
      headers: {
        'Authorization': getToken()
      },
      showUpload: false,
      height: document.documentElement.clientHeight - 180 + 'px;',
      deptName: '',  level: 3,
      roles: [],
      roleIdList: [], // 多选时使用
      defaultProps: { children: 'children', label: 'name', isLeaf: 'leaf' },
      permission: {
        add: [ 'sys_grade_view'],
        edit: [ 'sys_grade_view'],
        del: [ 'sys_grade_view']
      },
      enabledTypeOptions: [
        { key: 'false', display_name: '未冻结' },
        { key: 'true', display_name: '冻结' }
      ],
      rules: {
        name: [
          { required: true, message: '请输入班级名称', trigger: 'blur' },
        ]
      },
      /*是否显示班级列表*/
      showClassList:false,
      classLists:[],
      classListsTotal: 0,
      addDialog:false,
      classModal:{
        name: '',
        id :''
      }
    }
  },
  computed: {
    ...mapGetters([
      'user',
      'minioApi',
      'updateAvatarApi',
      'baseApi'
    ])
  },
  created() {

  },
  mounted: function() {
    const that = this
    window.onresize = function temp() {
      that.height = document.documentElement.clientHeight - 180 + 'px;'
    }
  },
  methods: {
    /*删除上传文件*/
    fileRemove(file, fileList){

    },
    /*文件上传之前*/
    beforeUpload(file){
      crud.downloadLoading=true
      /*限定导入格式*/
        let format=(file.name).substring(file.name.lastIndexOf("."),file.name.length)
      if (format!=='xlsx'){
        appUtils.showError("上传错误，只能上传.xlsx格式的文件")
        return false;
      }
    },
    /*文件上传成功之后*/
    uploadSuccess(res, file, fileList){
      crud.downloadLoading=true
      if (res.state){
        appUtils.showSuccess("导入成功,未导入数据："+res.data.errorList.length+"条")
        this.fileList=[]
        this.crud.refresh()
      }
      else {
        this.fileList=[]
        appUtils.showError(res.msg)
      }
    },
    /*文件上传失败*/
    uploadError(err, file, fileList){
      crud.downloadLoading=true
      appUtils.showError(err.msg)
      this.fileList=[]
    },
    // 新增前将多选的值设置为空
    [CRUD.HOOK.beforeToAdd]() {

    },
    [CRUD.HOOK.beforeToCU](crud) {

    },
    /*提交之前处理数据*/
    [CRUD.HOOK.afterValidateCU](crud) {

    },
    checkboxT(row, rowIndex) {

    },

    /**
     * 添加班级
     */
    addClass(row){
      dataUtils.setData("gradeId",row.id)
      this.showClassList=true
      this.classListsTotal=this.classLists.length
      this.classLists=row.classesList
    },

    /**
     *展示编辑框
     */
    showAddDialog(){
      this.addDialog=true
      this.classModal={}
    },

    /**
     * 添加班级列表
     */
    saveClass(){
      let that=this
      this.addDialog=false
      this.classModal.gradeId=dataUtils.getData("gradeId")
      if (this.classModal.id!=null){
        edit(this.classModal).then(res=>{
          if (res.state){
            getClassByGradeId(this.classModal.gradeId).then(res=>{
              if (res.state){
                this.classLists=res.data
              }
              else {
                appUtils.showError(res.msg)
              }
            })
            this.addDialog=false
            appUtils.showSuccess(res.msg)
          } else {
            this.addDialog=false
            appUtils.showError(res.msg)
          }
        })
      }
      else {
        add(this.classModal).then(res=>{
          if (res.state){
            this.addDialog=false
            appUtils.showSuccess(res.msg)
            that.crud.refresh()
          }else {
            this.addDialog=false
            appUtils.showError(res.msg)
          }
        })
      }
    },
    cancelSave(){
      this.addDialog=false
    },
    /**
     * 编辑班级
     */
    editClass(row){
      this.addDialog=true
      this.classModal.name=row.name
      this.classModal.id=row.id
    },
    delClass(row){
      row.gradeId=dataUtils.getData("gradeId")
      del(row).then(res=>{
        if (res.state){
          appUtils.showSuccess(res.msg)
        }
        else {
          appUtils.showError(res.msg)
        }
      })
    },
    clearCache(){
      dataUtils.removeData("gradeId");
      this.showClassList=false
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .vue-treeselect__control, ::v-deep .vue-treeselect__placeholder, ::v-deep .vue-treeselect__single-value {
  height: 30px;
  line-height: 30px;
}
</style>
